/**
 * 音频视频同步器
 */
var async = require('async')
	,fs = require('fs')
	,Image = require('canvas').Image
	,path = require('path')
	,Layer = require('./Layer/main')
	,config = require('../config');

var Synchronizer = function(audioDuration){
	//常用变量
	this.interval = 0.04;//同步的时间间隔 40ms-->0.04s	25帧
	this.audioDuration = audioDuration;
	this.eventJson = false;
	this.layer = new Layer();


	//私有变量
	this._currentTime = 0;
	this._recordCount = 0;
	this._records = false;


	/**
	 * 转换为图片方法
	 * @param callback	转换后的回调
	 */
	this.convert = function(callback){
		async.series([
			//1.得到json
			function(cb){
				this._getEventJson(cb)
			}.bind(this),
			//2.缓存图片
			function(cb){
				this._cacheImg(cb);
			}.bind(this),
			//3.绘制
			function(cb){
				async.whilst(
					function() { return this._currentTime < this.audioDuration}.bind(this),
					function(whileCB) {
						var json = this._getData(this._currentTime,this._currentTime + this.interval);
						this._currentTime += this.interval;
						this.layer.draw(json,function(){
							whileCB();
						},this._currentTime >= this.audioDuration);
					}.bind(this),
					function(err) {
						cb(err);
					}
				);
			}.bind(this)
		],function(err){
			callback(err);
		})
	}

	/**
	 * 缓存图片
	 * @param callback	缓存后的回调
	 * @private
	 */
	this._cacheImg = function(callback){
		var obj = {
			img : {},
			fileOrPpt : {}
		}

		async.each(this._records, function(record, cb) {
			if(record.class == "DRFileRecord"){//如果是图片 ppt file 类资源
				if(record.fileType == 1){//如果是图片
					if(!obj.img.hasOwnProperty(record.relativeSourcePath)){//并且没有存储上
						fs.readFile(path.join(config.originPath, record.relativeSourcePath), function(err, squid){
							var image = new Image();
							image.src = squid;
							obj.img[record.relativeSourcePath] = image;
							cb();
						});

					}
				}else{//如果是 ppt 或 文件 type == ppt or file
					if(!obj.fileOrPpt.hasOwnProperty(record.relativeSourcePath)){
						fs.readFile(path.join(config.originPath,  record.relativeSourcePath), function(err, squid){
							var image = new Image();
							image.src = squid;
							image.pageIndex = record.pageIndex;
							obj.fileOrPpt[record.relativeSourcePath] = image;
							cb();
						});
					}
				}

			}else
				cb();
		}.bind(this), function(err) {
			//初始化
			this.layer.init(obj);
			callback(err);
		}.bind(this));
	}


	/**
	 * 得到某段时间内的数据
	 * @param startTime	开始时间
	 * @param endTime	结束时间
	 * @private
	 */
	this._getData = function(startTime,endTime){
		console.log("开始时间："+startTime + ",结束时间："+endTime);
		startTime = parseFloat(startTime);
		endTime = parseFloat(endTime);
		var _recordFlag = false;
		var array = [];
		for(var i=0;i<this._recordCount;i++){
			var timestamp = parseFloat(this._records[i].timestamp);
			if(startTime <= timestamp){
				_recordFlag = true;

				//加入isAdd
				if(i > 0){
					var _j = i;
					while(this._records[--_j].isAdd ==  0){
						array.push(this._records[_j]);
						if(_j == 0)	break;
					}
				}
			}
			else
				continue;

			if(_recordFlag){
				if(endTime >= timestamp){
					array.push(this._records[i]);
				}
				else
					break;
			}
		}


		return array;
	}

	/**
	 * 得到event.json文件
	 * @param callback	得到后的回调
	 * @private
	 */
	this._getEventJson = function(callback){
		async.waterfall([
			function(cb){
				fs.readFile(config.originPath + "/event.json",{encoding:'utf-8'}, function (err,bytesRead) {
					cb(err,bytesRead);
				});
			}
		],function(err,result){
			if(err)
				callback(err);
			else{
				this.eventJson = JSON.parse(result);
				this._records = this.eventJson.records;
				this._recordCount = this._records.length;
				callback(null);
			}
		}.bind(this));
	}
};
module.exports = Synchronizer;